//
//  BrowseHistoryView.swift
//  YoruNeko
//
//  Created by  mahoPunch on 2021/6/24.
//

import SwiftUI


struct BrowseHistoryView: View {
   
    
    var callback:BrowseHistoryCallback?
    
    
    
    
    @StateObject var modelData:HistoryModelData = .init(with: HistoryManager.getCachedHistoryList())
    
//        .init(with: [
//        History(date_added: Date(), title: "google4", url: "www.google.com"),
//        History(date_added: Date(), title: "google4", url: "www.google.com"),
//        History(date_added: Date(), title: "google4", url: "www.google.com")
//    ])
    
    
    var currentFilteredHistoryList:[History]{

        return modelData.list.filter({ history in
            searchKeyword.isEmpty || history.title.containsIgnoringCase(find: searchKeyword) || YRNKUtil.isSubSequence(history.title, sub_str: searchKeyword) || history.url.containsIgnoringCase(find: searchKeyword)
        })
    }
    

    struct SearchKeyPrefKey:PreferenceKey{
        static var defaultValue: String  = ""
        static func reduce(value: inout String, nextValue: () -> String) {
            
        }
    }
    
    @State var searchKeyword: String = ""
    @State var isEditing = false
    @State var isAlertPresented = false
    
    @State var isSelectMode = false
    @State var isloading = true
    @State var selectedList = Set.init([History].init())
    
    var histories:[History]{
        return currentFilteredHistoryList
    }
    
    @State var _historyGroup = [[History]].init()
    
    var historyGroup: [[History]] {
        var result: [[History]] = [[History]].init(repeating: [History].init(), count: 3)
        for history in histories {
            if YRNKUtil.isSameDay(date: history.date_added){
                result[0].append(history)
            }else if YRNKUtil.isSameWeek(date: history.date_added){
                result[1].append(history)
            }else{
                result[2].append(history)
            }
        }
        return result
    }
    
    
    private var 历史_副标题:String{
        get{
            if isSelectMode{
                return "-已选\(selectedList.count)项"
            }
            else
            {
                return ""
            }
            
        }
    }
    var body: some View {
        NavigationView{
            
            VStack {//占位用
                
                BookmarkSearchTab(searchKeyword: $searchKeyword, isEditing: $isEditing).padding(.vertical, 5)
                    .preference(key: SearchKeyPrefKey.self, value: searchKeyword)
                    .onPreferenceChange(SearchKeyPrefKey.self, perform: { value in
                        load()
                    })
                //BookmarkSearchTab(searchKeyword: $searchKeyword, isEditing: $isEditing).padding(.vertical, 5)
                if isloading {
                    Spacer()
                    ProgressView()
                    Spacer()
                }
                else{
                    BrowseHistoryList(isSelectMode: $isSelectMode, selectedList: $selectedList, onDeleteRow: {
                        id in
                        modelData.list.remove(at: modelData.list.firstIndex(where:{ (h:History)->Bool in
                            return h.id == id
                        })!
                        )
                        callback?.deleteHistory(by: id)
                    },onRowClick: {
                        id in
                        //callback?.goToView(by: .IndexView, sender: self, with: [RequestArgumentKey.wd.rawValue:self.getHistoryById(id: id).url])
                        callback?.goToView(to: .IndexView, from: .HistoryView, intent: .Default, with: [.wd:self.getHistoryById(id: id).url])
                    },_historyGroup: _historyGroup)
                }
                
            }/*VStack*/
            .padding(.top, 5)
            .navigationTitle("历史\(self.历史_副标题)")
            .navigationBarItems(leading:
                                    Button {
                                        if isSelectMode{
                                            isSelectMode = false
                                        }
                                        else{
                                            callback?.goBack()
                                        }
                                        
                                    } label: {
                                        if isSelectMode{
                                            Text("取消")
                                        }
                                        else{
                                            HStack {
                                                Image(systemName: "chevron.backward")
                                                Text("返回")
                                            }
                                        }
                                        
                                    },
                                trailing: Button {
                                    isAlertPresented = true
                                    
                                } label: {
                                    if isSelectMode{
                                        Text("删除")
                                            .foregroundColor(.red)
                                    }
                                    else{
                                        if !modelData.list.isEmpty {
                                            Text("清空")
                                                .foregroundColor(.red)
                                        }
                                    }
                                    
                                }
            )
            .navigationBarTitleDisplayMode(.inline)
            .onAppear(perform: {
                YRNKLog("HistoryListVStack", msg: "this stack onAppear")
                load()
            })
            
        }.alert(isPresented: $isAlertPresented,
                content: {
            Alert(title: Text("警告").foregroundColor(.red),
                  message: isSelectMode ? Text("确定清除所选的\(selectedList.count)条记录吗") : Text("你确定清空所有历史记录吗"),
                  primaryButton: .destructive(Text("确定"), action: {
                    isAlertPresented = false
                    if isSelectMode{
                        performMultiDelete()
                    }
                    else{
                        performClearAll()
                    }
                    
                  }),
                  secondaryButton: .cancel(Text("不了"))
                )
                })
       
    }
    
    private func load(){
        isloading = true
        YRNKLog("historylist is loading", msg: isloading.description)
        YRNKSharedThreadPool.dispatchTask(operation: {
            let list = historyGroup
            YRNKSharedThreadPool.dispatchUITask(ui_operation: {
                self._historyGroup = list
                self.isloading = false
                YRNKLog("historylist is loading ", msg: isloading.description)
                //YRNKLog("HistoryView", msg: "did load")
            })
        })
    }
    
    func performMultiDelete(){
        isSelectMode = false
        modelData.list = modelData.list.filter({
            !selectedList.contains($0)
        })
        
        callback?.deleteMultiHistory(IDs: selectedList.compactMap({
            return $0.id
        }))
    }
    
    func performClearAll(){
        modelData.list.removeAll()
        callback?.clear()
    }
    
    func getHistoryById(id:UUID)->History{
        return currentFilteredHistoryList.first(where: {
            $0.id == id
        })!
        
    }
}

struct BrowseHistoryView_Previews: PreviewProvider {
    static var previews: some View {
        BrowseHistoryView()
    }
}
